// 默认配置
const DEFAULT_CONFIG = {
    translationEngine: 'youdao',
    sourceLanguage: 'auto',
    targetLanguage: 'zh-CN',
    displayMode: 'replace',
    autoTranslate: false,
    openaiApiKey: '',
    openaiBaseUrl: 'https://api.openai.com/v1',
    openaiModel: 'gpt-3.5-turbo',
    youdaoApiKey: '',
    youdaoAppSecret: '',
    maxTextLength: 2000,
    requestTimeout: 30,
    cacheEnabled: true,
    debugMode: false
};

// 获取当前选择的模型值
function getModelValue() {
    const modelInput = document.getElementById('openaiModel');
    const modelPreset = document.getElementById('openaiModelPreset');

    // 优先使用输入框的自定义模型
    if (modelInput.value.trim()) {
        return modelInput.value.trim();
    }

    // 如果输入框为空，使用下拉框选择的预设模型
    return modelPreset.value || DEFAULT_CONFIG.openaiModel;
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initTabs();
    loadSettings();
    setupEventListeners();
});

// 初始化选项卡
function initTabs() {
    const tabs = document.querySelectorAll('.tab');
    const tabContents = document.querySelectorAll('.tab-content');

    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const targetTab = tab.dataset.tab;

            // 切换选项卡状态
            tabs.forEach(t => t.classList.remove('active'));
            tabContents.forEach(content => content.classList.remove('active'));

            tab.classList.add('active');
            document.getElementById(targetTab).classList.add('active');
        });
    });
}

// 设置事件监听器
function setupEventListeners() {
    // 翻译引擎选择变化
    const engineRadios = document.querySelectorAll('input[name="translationEngine"]');
    engineRadios.forEach(radio => {
        radio.addEventListener('change', handleEngineChange);
    });

    // 表单验证
    const formControls = document.querySelectorAll('.form-control');
    formControls.forEach(control => {
        control.addEventListener('blur', () => validateField(control));
        control.addEventListener('input', () => {
            control.classList.remove('error');
        });
    });

    // 密码显示切换按钮
    const passwordToggles = document.querySelectorAll('.password-toggle');
    passwordToggles.forEach(toggle => {
        toggle.addEventListener('click', (e) => {
            const fieldId = e.target.getAttribute('data-field');
            togglePassword(fieldId);
        });
    });

    // 测试连接按钮
    const testOpenAI = document.getElementById('testOpenAI');
    if (testOpenAI) {
        testOpenAI.addEventListener('click', testOpenAIConnection);
    }

    const testYoudao = document.getElementById('testYoudao');
    if (testYoudao) {
        testYoudao.addEventListener('click', testYoudaoConnection);
    }

    // 重置按钮
    const resetDefaults = document.getElementById('resetDefaults');
    if (resetDefaults) {
        resetDefaults.addEventListener('click', resetToDefaults);
    }

    // 保存设置按钮
    const saveSettingsBtn = document.getElementById('saveSettings');
    if (saveSettingsBtn) {
        saveSettingsBtn.addEventListener('click', saveSettings);
    }

    // 导出设置按钮
    const exportSettingsBtn = document.getElementById('exportSettings');
    if (exportSettingsBtn) {
        exportSettingsBtn.addEventListener('click', exportSettings);
    }

    // 导入设置按钮
    const importSettingsBtn = document.getElementById('importSettings');
    if (importSettingsBtn) {
        importSettingsBtn.addEventListener('click', importSettings);
    }

    // 模型选择事件监听器
    const modelPreset = document.getElementById('openaiModelPreset');
    const modelInput = document.getElementById('openaiModel');

    if (modelPreset && modelInput) {
        // 当预设下拉框变化时
        modelPreset.addEventListener('change', function() {
            if (this.value) {
                modelInput.value = '';
                modelInput.placeholder = '已选择预设模型';
            } else {
                modelInput.placeholder = '输入自定义模型名称';
            }
        });

        // 当自定义输入框变化时
        modelInput.addEventListener('input', function() {
            if (this.value.trim()) {
                modelPreset.value = '';
            }
        });

        // 当自定义输入框获得焦点时
        modelInput.addEventListener('focus', function() {
            modelPreset.value = '';
            this.placeholder = '输入自定义模型名称';
        });
    }
}

// 处理翻译引擎变化
function handleEngineChange(event) {
    const engine = event.target.value;
    const openaiConfig = document.getElementById('openaiConfig');
    const youdaoConfig = document.getElementById('youdaoConfig');

    // 更新选中状态
    document.querySelectorAll('.radio-option').forEach(option => {
        option.classList.remove('selected');
    });
    event.target.closest('.radio-option').classList.add('selected');

    // 显示对应配置
    openaiConfig.classList.toggle('active', engine === 'openai');
    youdaoConfig.classList.toggle('active', engine === 'youdao');
}

// 加载设置
async function loadSettings() {
    try {
        const settings = await chrome.storage.sync.get(DEFAULT_CONFIG);

        // 填充基本设置
        document.getElementById('sourceLanguage').value = settings.sourceLanguage;
        document.getElementById('targetLanguage').value = settings.targetLanguage;
        document.getElementById('displayMode').value = settings.displayMode;
        document.getElementById('autoTranslate').value = settings.autoTranslate.toString();

        // 填充翻译引擎设置
        const engineRadio = document.querySelector(`input[name="translationEngine"][value="${settings.translationEngine}"]`);
        if (engineRadio) {
            engineRadio.checked = true;
            handleEngineChange({ target: engineRadio });
        }

        // 填充 OpenAI 设置
        document.getElementById('openaiApiKey').value = settings.openaiApiKey;
        document.getElementById('openaiBaseUrl').value = settings.openaiBaseUrl;

        // 处理模型选择
        const openaiModel = settings.openaiModel;
        const modelInput = document.getElementById('openaiModel');
        const modelPreset = document.getElementById('openaiModelPreset');

        // 检查是否为预设模型
        const presetOptions = Array.from(modelPreset.options).map(option => option.value);
        if (presetOptions.includes(openaiModel)) {
            modelPreset.value = openaiModel;
            modelInput.value = '';
        } else {
            modelPreset.value = '';
            modelInput.value = openaiModel;
        }

        // 填充有道设置
        document.getElementById('youdaoApiKey').value = settings.youdaoApiKey;
        document.getElementById('youdaoAppSecret').value = settings.youdaoAppSecret;

        // 填充高级设置
        document.getElementById('maxTextLength').value = settings.maxTextLength;
        document.getElementById('requestTimeout').value = settings.requestTimeout;
        document.getElementById('cacheEnabled').value = settings.cacheEnabled.toString();
        document.getElementById('debugMode').value = settings.debugMode.toString();

    } catch (error) {
        console.error('Failed to load settings:', error);
        showAlert('加载设置失败：' + error.message, 'error');
    }
}

// 保存设置
async function saveSettings() {
    console.log('saveSettings function called');
    try {
        // 验证必填字段
        if (!validateSettings()) {
            console.log('Settings validation failed');
            return;
        }

        const settings = {
            translationEngine: document.querySelector('input[name="translationEngine"]:checked').value,
            sourceLanguage: document.getElementById('sourceLanguage').value,
            targetLanguage: document.getElementById('targetLanguage').value,
            displayMode: document.getElementById('displayMode').value,
            autoTranslate: document.getElementById('autoTranslate').value === 'true',
            openaiApiKey: document.getElementById('openaiApiKey').value.trim(),
            openaiBaseUrl: document.getElementById('openaiBaseUrl').value.trim() || DEFAULT_CONFIG.openaiBaseUrl,
            openaiModel: getModelValue(),
            youdaoApiKey: document.getElementById('youdaoApiKey').value.trim(),
            youdaoAppSecret: document.getElementById('youdaoAppSecret').value.trim(),
            maxTextLength: parseInt(document.getElementById('maxTextLength').value),
            requestTimeout: parseInt(document.getElementById('requestTimeout').value),
            cacheEnabled: document.getElementById('cacheEnabled').value === 'true',
            debugMode: document.getElementById('debugMode').value === 'true'
        };

        console.log('Saving settings to chrome.storage:', settings);
        await chrome.storage.sync.set(settings);
        console.log('Settings saved successfully');
        showAlert('设置保存成功！', 'success');

        // 通知其他页面配置已更新
        chrome.runtime.sendMessage({ action: 'settingsUpdated' });
        console.log('Settings update notification sent');

    } catch (error) {
        console.error('Failed to save settings:', error);
        showAlert('保存设置失败：' + error.message, 'error');
    }
}

// 验证设置
function validateSettings() {
    const engine = document.querySelector('input[name="translationEngine"]:checked').value;

    if (engine === 'openai') {
        const apiKey = document.getElementById('openaiApiKey').value.trim();
        const baseUrl = document.getElementById('openaiBaseUrl').value.trim();

        if (!apiKey) {
            showAlert('请输入 OpenAI API Key', 'error');
            document.getElementById('openaiApiKey').classList.add('error');
            return false;
        }

        if (baseUrl && !isValidUrl(baseUrl)) {
            showAlert('请输入有效的 Base URL', 'error');
            document.getElementById('openaiBaseUrl').classList.add('error');
            return false;
        }

    } else if (engine === 'youdao') {
        const apiKey = document.getElementById('youdaoApiKey').value.trim();
        const appSecret = document.getElementById('youdaoAppSecret').value.trim();

        if (!apiKey) {
            showAlert('请输入有道应用 Key', 'error');
            document.getElementById('youdaoApiKey').classList.add('error');
            return false;
        }

        if (!appSecret) {
            showAlert('请输入有道应用密钥', 'error');
            document.getElementById('youdaoAppSecret').classList.add('error');
            return false;
        }
    }

    // 验证数值字段
    const maxTextLength = parseInt(document.getElementById('maxTextLength').value);
    const requestTimeout = parseInt(document.getElementById('requestTimeout').value);

    if (maxTextLength < 100 || maxTextLength > 8000) {
        showAlert('最大文本长度应在 100-8000 之间', 'error');
        document.getElementById('maxTextLength').classList.add('error');
        return false;
    }

    if (requestTimeout < 10 || requestTimeout > 120) {
        showAlert('请求超时时间应在 10-120 秒之间', 'error');
        document.getElementById('requestTimeout').classList.add('error');
        return false;
    }

    return true;
}

// 验证字段
function validateField(field) {
    field.classList.remove('error');

    if (field.type === 'url' && field.value && !isValidUrl(field.value)) {
        field.classList.add('error');
        return false;
    }

    if (field.type === 'number') {
        const value = parseInt(field.value);
        const min = parseInt(field.min);
        const max = parseInt(field.max);

        if (value < min || value > max) {
            field.classList.add('error');
            return false;
        }
    }

    return true;
}

// 验证URL格式
function isValidUrl(string) {
    try {
        new URL(string);
        return true;
    } catch (_) {
        return false;
    }
}

// 测试 OpenAI 连接
async function testOpenAIConnection() {
    console.log('testOpenAIConnection called');
    const testResult = document.getElementById('openaiTestResult');
    if (!testResult) {
        console.error('openaiTestResult element not found');
        return;
    }
    testResult.className = 'test-result';
    testResult.textContent = '测试中...';
    testResult.style.display = 'block';
    console.log('OpenAI test started');

    try {
        const apiKey = document.getElementById('openaiApiKey').value.trim();
        const baseUrl = document.getElementById('openaiBaseUrl').value.trim() || DEFAULT_CONFIG.openaiBaseUrl;
        const model = getModelValue();

        if (!apiKey) {
            throw new Error('请先输入 API Key');
        }

        const response = await fetch(`${baseUrl}/chat/completions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify({
                model: model,
                messages: [{ role: 'user', content: 'Hello' }],
                max_tokens: 5
            })
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.error?.message || `HTTP ${response.status}`);
        }

        testResult.className = 'test-result success';
        testResult.textContent = '✅ 连接成功！';

    } catch (error) {
        testResult.className = 'test-result error';
        testResult.textContent = `❌ 连接失败：${error.message}`;
    }
}

// 测试有道连接
async function testYoudaoConnection() {
    console.log('testYoudaoConnection called');
    const testResult = document.getElementById('youdaoTestResult');
    if (!testResult) {
        console.error('youdaoTestResult element not found');
        return;
    }
    testResult.className = 'test-result';
    testResult.textContent = '测试中...';
    testResult.style.display = 'block';
    console.log('Youdao test started');

    try {
        const apiKey = document.getElementById('youdaoApiKey').value.trim();
        const appSecret = document.getElementById('youdaoAppSecret').value.trim();

        if (!apiKey || !appSecret) {
            throw new Error('请先输入应用 Key 和密钥');
        }

        console.log('🧪 Testing Youdao API via background script...');

        // 使用background script中的翻译管理器进行测试
        chrome.runtime.sendMessage({ action: 'testAPI' }, (response) => {
            console.log('📥 Received API test response:', response);

            if (chrome.runtime.lastError) {
                console.error('❌ Chrome runtime error:', chrome.runtime.lastError);
                testResult.className = 'test-result error';
                testResult.textContent = `❌ 连接失败：${chrome.runtime.lastError.message}`;
                return;
            }

            if (response && response.success) {
                console.log('✅ Youdao API test successful:', response.result);
                testResult.className = 'test-result success';
                testResult.textContent = `✅ 连接成功！翻译结果："${response.result.translated}" (耗时: ${response.result.duration}ms)`;
            } else {
                console.error('❌ Youdao API test failed:', response);
                testResult.className = 'test-result error';
                testResult.textContent = `❌ 连接失败：${response.error || '未知错误'}`;
            }
        });

        // 设置超时检查
        setTimeout(() => {
            if (testResult.textContent === '测试中...') {
                console.warn('⏰ API test timeout after 25 seconds');
                testResult.className = 'test-result error';
                testResult.textContent = '❌ 连接超时，请检查网络或API配置';
            }
        }, 25000);

    } catch (error) {
        console.error('❌ Youdao test setup error:', error);
        testResult.className = 'test-result error';
        testResult.textContent = `❌ 连接失败：${error.message}`;
    }
}

// 生成有道签名
async function generateYoudaoSign(query, salt, appSecret) {
    const str = appSecret + query + salt;
    const encoder = new TextEncoder();
    const data = encoder.encode(str);
    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}

// 切换密码可见性
function togglePassword(fieldId) {
    const field = document.getElementById(fieldId);
    const button = field.nextElementSibling;

    if (field.type === 'password') {
        field.type = 'text';
        button.textContent = '🙈';
    } else {
        field.type = 'password';
        button.textContent = '👁️';
    }
}

// 重置为默认设置
async function resetToDefaults() {
    if (!confirm('确定要重置所有设置到默认状态吗？此操作不可恢复。')) {
        return;
    }

    try {
        await chrome.storage.sync.clear();
        await chrome.storage.sync.set(DEFAULT_CONFIG);
        await loadSettings();
        showAlert('已重置为默认设置', 'success');
    } catch (error) {
        console.error('Failed to reset settings:', error);
        showAlert('重置失败：' + error.message, 'error');
    }
}

// 导出设置
async function exportSettings() {
    console.log('exportSettings called');
    try {
        const settings = await chrome.storage.sync.get(DEFAULT_CONFIG);
        console.log('Retrieved settings for export:', settings);
        const dataStr = JSON.stringify(settings, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);

        const exportName = `translator-settings-${new Date().toISOString().slice(0,10)}.json`;

        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportName);
        linkElement.click();

        showAlert('设置导出成功', 'success');
    } catch (error) {
        console.error('Failed to export settings:', error);
        showAlert('导出失败：' + error.message, 'error');
    }
}

// 导入设置
function importSettings() {
    console.log('importSettings called');
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    console.log('File input created');

    input.onchange = async (event) => {
        const file = event.target.files[0];
        if (!file) return;

        try {
            const text = await file.text();
            const settings = JSON.parse(text);

            // 验证设置格式
            if (!settings.translationEngine || !settings.targetLanguage) {
                throw new Error('无效的设置文件格式');
            }

            await chrome.storage.sync.clear();
            await chrome.storage.sync.set(settings);
            await loadSettings();

            showAlert('设置导入成功', 'success');
        } catch (error) {
            console.error('Failed to import settings:', error);
            showAlert('导入失败：' + error.message, 'error');
        }
    };

    input.click();
}

// 显示提示消息
function showAlert(message, type) {
    console.log('showAlert called:', message, type);
    const alert = document.getElementById('alert');
    if (alert) {
        alert.textContent = message;
        alert.className = `alert alert-${type} show`;
        console.log('Alert element found and updated');

        // 3秒后自动隐藏
        setTimeout(() => {
            alert.classList.remove('show');
        }, 3000);
    } else {
        console.error('Alert element not found!');
    }
}